package com.ankiang.treeprint.fragment.components;

import android.content.Context;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ankiang.treeprint.R;
import com.ankiang.treeprint.base.BaseFragment;
import com.ankiang.treeprint.fragment.util.TRUtils;
import com.ankiang.treeprint.lib.Group;
import com.ankiang.treeprint.lib.annotation.Widget;
import com.ankiang.treeprint.model.TRItemNode;
import com.ankiang.treeprint.model.TRRelationShip;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIPagerAdapter;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author cginechen
 * @date 2017-09-13
 */

@Widget(group = Group.Home, widgetClass = TRCalculatorFragment.class, iconRes = R.drawable.ic_icon_calculator)
public class TRCalculatorFragment extends BaseFragment {
//    @BindView(R.id.topbar) QMUITopBar mTopBar;
//    @BindView(R.id.pager) QMUIViewPager mViewPager;

    @BindView(R.id.femaleRadioButton)
    RadioButton femaleRadioButton;

    @BindView(R.id.maleRadioButton)
    RadioButton maleRadioButton;

    @BindView(R.id.inputText)
    TextView inputText;

    @BindView(R.id.outputText)
    TextView outputText;
    @BindView(R.id.outputReverseText)
    TextView outputReverseText;

    @BindView(R.id.fatherButton)
    Button fatherButton;

    @BindView(R.id.motherButton)
    Button motherButton;

    @BindView(R.id.sonButton)
    Button sonButton;

    @BindView(R.id.daughterButton)
    Button daughterButton;

    @BindView(R.id.elderBrotherButton)
    Button elderBrotherButton;

    @BindView(R.id.youngerBrotherButton)
    Button youngerBrotherButton;

    @BindView(R.id.elderSisterButton)
    Button elderSisterButton;

    @BindView(R.id.youngerSisterButton)
    Button youngerSisterButton;

    @BindView(R.id.husbandButton)
    Button husbandButton;

    @BindView(R.id.wifeButton)
    Button wifeButton;

    @BindView(R.id.deButton)
    Button deButton;

    @BindView(R.id.delButton)
    Button delButton;

    @BindView(R.id.clearButton)
    Button clearButton;

    @BindView(R.id.equalButton)
    Button equalButton;

    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;

    TRRelationShip machine;

    private List<String> mItems = new ArrayList<>();
    private ArrayList mReverseResult;
    private ArrayList mResult;


    @Override
    protected View onCreateView() {
        FrameLayout layout = (FrameLayout) LayoutInflater.from(getActivity()).inflate(R.layout.tr_fragment_calculator, null);
        ButterKnife.bind(this, layout);

        machine = new TRRelationShip();

        initListener();
        initData(5);
        initTopBar();
        initPagers();
        return layout;
    }

    private void initListener() {
        View.OnClickListener listener = (v) -> {
            Button button = (Button) v;
            String input = button.getText().toString();
            handle(input);
        };

        fatherButton.setOnClickListener(listener);
        motherButton.setOnClickListener(listener);
        sonButton.setOnClickListener(listener);
        daughterButton.setOnClickListener(listener);
        elderBrotherButton.setOnClickListener(listener);
        youngerBrotherButton.setOnClickListener(listener);
        elderSisterButton.setOnClickListener(listener);
        youngerSisterButton.setOnClickListener(listener);
        husbandButton.setOnClickListener(listener);
        wifeButton.setOnClickListener(listener);
        equalButton.setOnClickListener(v -> {
            handle("");
        });

        maleRadioButton.setOnClickListener(v -> {
            handle("");
        });
        femaleRadioButton.setOnClickListener(v -> {
            handle("");
        });

        deButton.setOnClickListener(listener);

        delButton.setOnClickListener(v -> {
            if (mItems.isEmpty()) {
                return;
            }
            mItems.remove(mItems.size() - 1);

            handle("");
//
//            String s = myJoin("", mItems);
//            inputText.setText(s);
//            try {
//                s = calculate(s);
//            } catch (Exception e) {
//                Toast.makeText(getActivity(), "错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//            outputText.setText(s);

        });
        clearButton.setOnClickListener(v -> {
            inputText.setText("");
            outputText.setText("");
            outputReverseText.setText("");
            if (mItems != null) {
                mItems.clear();
            }
            if (mResult != null) {
                mResult.clear();
            }
            if (mReverseResult != null) {
                mReverseResult.clear();
            }
        });

        outputText.setOnClickListener(v -> {
            TRListItemFragment fragment = new TRListItemFragment();
            fragment.setTitle(V(R.string.calculator_i_call_it));
            ArrayList<TRItemNode> tmpList = new ArrayList<>();
            if (mResult == null || mResult.size() <= 1) {
                return;
            }
            Iterator<String> iter = mResult.iterator();
            while (iter.hasNext()) {
                String s = iter.next();
                TRItemNode tmp = new TRItemNode();
                tmp.setCallname(s);
                tmp.setName(null);
                tmpList.add(tmp);
            }
            fragment.setItemList(tmpList);
            startFragment(fragment);
        });
        outputReverseText.setOnClickListener(v -> {
            TRListItemFragment fragment = new TRListItemFragment();
            fragment.setTitle(V(R.string.calculator_it_call_me));
            ArrayList<TRItemNode> tmpList = new ArrayList<>();
            if (mReverseResult == null || mReverseResult.size() <= 1) {
                return;
            }
            Iterator<String> iter = mReverseResult.iterator();
            while (iter.hasNext()) {
                String s = iter.next();
                TRItemNode tmp = new TRItemNode();
                tmp.setCallname(s);
                tmp.setName(null);
                tmpList.add(tmp);
            }
            fragment.setItemList(tmpList);
            startFragment(fragment);
        });

    }

    private void handle(String input) {

        String last = "";

        int idx = mItems.size() - 1;
        if (idx >= 0) {
            last = mItems.get(idx);
        }

        // 第一个不能是【的】
        // 已经删除空了，也要清输入输出
        if (mItems.size() == 0 && ("的".equals(input) || "".equals(input))) {
            inputText.setText("");
            outputText.setText("");
            outputReverseText.setText("");
            return;
        }
        if ("的".equals(input)) {
            if (!"的".equals(last)) {
                mItems.add(input);
            }
            // 如果最后一个是的，就不再加了
        } else if ("的".equals(last)) {
            if (!"的".equals(input) && !"".equals(input)) {
                mItems.add(input);
            }
        } else {
            // 如果input=""则是重新计算，不需要删除
            if (!mItems.isEmpty() && !"".equals(input)) {
                mItems.remove(mItems.size() - 1);
            }
            // 如果是""，不需要添加
            if (!"".equals(input)) {
                mItems.add(input);
            }
        }

        String sInput = TRUtils.myJoin("", mItems);
        inputText.setText(sInput);
        String s = sInput;

        int sex = 1;
        if (femaleRadioButton.isChecked()) {
            sex = 0;
        }

        if (mItems.size() >= 1 && !input.equals("的")) {
            try {
                s = calculate(sInput, sex, false);
                outputText.setText(s);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            try {
                s = calculate(sInput, sex, true);
                outputReverseText.setText(s);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

    }

    private String calculate(String s, int sex, boolean reverse) {
        ArrayList res = machine.convert(s, sex, reverse);
        if (reverse) {
            mReverseResult = res;
        } else {
            mResult = res;
        }
        String text = TRUtils.myJoin("/", res);
        return text;
    }

    private void initData(int count) {
//        mItems.add("父");
    }

    void initTopBar() {
        mTopBar.setTitle(V(R.string.explore_calculator));

        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popBackStack();
            }
        });

//        mTopBar.addRightTextButton(R.string.cancel,QMUIViewHelper.generateViewId()).setOnClickListener(v->{
//            popBackStack();
//        });

    }


    private void initPagers() {
        QMUIPagerAdapter pagerAdapter = new QMUIPagerAdapter() {

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public int getCount() {
                return mItems.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mItems.get(position);
            }

            @Override
            protected Object hydrate(ViewGroup container, int position) {
                return new ItemView(getContext());
            }

            @Override
            protected void populate(ViewGroup container, Object item, int position) {
                ItemView itemView = (ItemView) item;
                itemView.setText(mItems.get(position));
                container.addView(itemView);
            }

            @Override
            protected void destroy(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }
        };
        //setPageTransformer默认采用ViewCompat.LAYER_TYPE_HARDWARE， 但它在某些4.x的国产机下会crash
        boolean canUseHardware = Build.VERSION.SDK_INT >= 21;
//        mViewPager.setPageTransformer(false, new CardTransformer(),
//                canUseHardware ? ViewCompat.LAYER_TYPE_HARDWARE : ViewCompat.LAYER_TYPE_SOFTWARE);
//        mViewPager.setInfiniteRatio(500);
//        mViewPager.setEnableLoop(true);
//        mViewPager.setAdapter(pagerAdapter);
    }

    static class ItemView extends FrameLayout {
        private TextView mTextView;

        public ItemView(Context context) {
            super(context);
            mTextView = new TextView(context);
            mTextView.setTextSize(20);
            mTextView.setTextColor(ContextCompat.getColor(context, R.color.app_color_theme_5));
            mTextView.setGravity(Gravity.CENTER);
            mTextView.setBackgroundColor(ContextCompat.getColor(context, R.color.qmui_config_color_white));
            int size = QMUIDisplayHelper.dp2px(context, 300);
            LayoutParams lp = new LayoutParams(size, size);
            lp.gravity = Gravity.CENTER;
            addView(mTextView, lp);
        }

        public void setText(CharSequence text) {
            mTextView.setText(text);
        }
    }
}
